package com.cskaoyan.service;

import com.cskaoyan.bean.Address;
import com.cskaoyan.bean.AddressExample;
import com.cskaoyan.mapper.AddressMapper;
import com.cskaoyan.vo.AddressItemsVo;
import com.cskaoyan.vo.AddressVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    AddressMapper addressMapper;

    /**
     * 功能:收货地址页面
     * 作者:whj
     */
    @Override
    public AddressVo query(Integer page, Integer limit, String sort, String order, Integer userId, String name) {
        //分页和排序
        //页码、数据量
        PageHelper.startPage(page, limit); //mybatis在构建sql语句 👉 会构造limit和offset

        AddressExample addressExample = new AddressExample();
        addressExample.setOrderByClause(sort + " " + order);//${}做Sql拼接
        //根据useId和name查询
        AddressExample.Criteria criteria = addressExample.createCriteria();
        if(userId != null && !"".equals(userId)){
            criteria.andUserIdEqualTo(userId);
        }
        if(name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<Address> addresses = addressMapper.selectByExample(addressExample);

        //total != users.size();
        //total是满足条件的所有的数据量 👉 而不是当前的limit
        //可以通过PageInfo获得分页信息
        PageInfo<Address> addressPageInfo = new PageInfo<>(addresses);//查询结果放进来
        Long total = addressPageInfo.getTotal();//总的数据量 👉 select count(*) 条件是byExample

        AddressVo addressVo = new AddressVo();
        List<AddressItemsVo> addressItemsVos = new ArrayList<>();
        for (Address address : addresses) {
            AddressItemsVo itemsVo = new AddressItemsVo();
            itemsVo.setIsDefault(address.getIsDefault());
            itemsVo.setAreaId(address.getAreaId());
            itemsVo.setAddress(address.getAddress());
            itemsVo.setName(address.getName());
            itemsVo.setMobile(address.getMobile());
            itemsVo.setId(address.getId());
            itemsVo.setCityId(address.getCityId());
            itemsVo.setUserId(address.getUserId());
            itemsVo.setProvinceId(address.getProvinceId());
            String area = addressMapper.selectRegionByPrimaryKey(address.getAreaId());
            itemsVo.setArea(area);
            String province = addressMapper.selectRegionByPrimaryKey(address.getProvinceId());
            itemsVo.setProvince(province);
            String city = addressMapper.selectRegionByPrimaryKey(address.getCityId());
            itemsVo.setCity(city);
            addressItemsVos.add(itemsVo);
        }
        addressVo.setItems(addressItemsVos);
        addressVo.setTotal(total);
        return addressVo;
    }
}
